package demo

import (
	"common/model"
	"common/pkg"
	"common/response"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

func ArgsViews(ctx *gin.Context) {
	var school SchoolReq
	err := ctx.BindQuery(&school)
	if err != nil {
		response.Fail(ctx, err.Error())
		return
	}

	user := &model.User{
		Username: "小明",
		Email:    "xiaoming@example.com",
		Age:      25,
		IsActive: true,
	}

	af, err := pkg.Engine.Insert(user)
	if err != nil {
		log.Printf("添加用户失败：%v", err)
		return
	}

	log.Println(af)

	response.Ok(ctx)
}

func FormViews(ctx *gin.Context) {
	name := ctx.PostForm("name")
	age := ctx.DefaultPostForm("age", "18")
	fmt.Print(name, age)
	ctx.Writer.Write([]byte("Hi, FormViews"))

}

// MapViews 方式一（结构体）
func MapViews(ctx *gin.Context) {

	//定义接口提，多的字段会被过滤，少的字段会被默认值
	var person PersonReq
	err := ctx.BindJSON(&person)

	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	ctx.Writer.Write([]byte("Hi, MapViews"))

}

// MapViews2 方式二 （序列化）
func MapViews2(ctx *gin.Context) {
	//方式二 （序列化）
	dataBytes, _ := ctx.GetRawData()
	var m map[string]interface{}
	_ = json.Unmarshal(dataBytes, &m)
	ctx.JSON(http.StatusOK, m)
}

// FileViews 上传下载文件
func FileViews(ctx *gin.Context) {

	file, _ := ctx.FormFile("file")

	filePath := "./file_2022_04_12" + file.Filename

	err := ctx.SaveUploadedFile(file, filePath)
	if err != nil {
		return
	}

	ctx.FileAttachment(filePath, file.Filename)
}
